package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.StreamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {

        // 查询缓存
        List<String> shopTypeListJson = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        if (CollectionUtil.isNotEmpty(shopTypeListJson)) { // 命中
            return Result.ok(StreamUtil.mapToBean(shopTypeListJson.stream(), ShopType.class));
        }

        // 查询数据库
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
        if (CollectionUtil.isNotEmpty(shopTypeList)) {
            // 写回缓存, 默认缓存30分钟
            stringRedisTemplate.opsForList()
                    .rightPushAll(CACHE_SHOP_TYPE_KEY, StreamUtil.mapToJsonStr(shopTypeList.stream()));
            stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        }
        return Result.ok(shopTypeList);
    }
}
